Swift Memory Management - Autorelease pool

Shantaram Kokate
2 min readMar 15, 2019
  • In swift, UIApplication handles the application’s Autorelease pool. Being a developer we don’t have to use the autorelease.
  • Autorelease pool blocks provide a mechanism whereby you can release ownership of an object,
  • In an iOS app, the main function is running in an autorelease pool. A drain operation of that pool will happen at the end of every main run loop.
  • A delay-release is required in development, sometimes we will want a variable lives longer than its scope (such as a callee function), so we can keep using it later.
  • In the Swift project, we have @UIApplicationMain. There is no need to add neither main file nor the main method like objective-c. Even if we create our own main.swift as an entry point of the app, there is no need to add anything related to the autorelease pool.

How autorelease work :

Problem :

Now we need to know the autorelease object. Suppose you own an object inside a method and returning that object. Receiver we will get a null object. You know why?.🤔

As we know, a temporary object will get release once its scope end.

In this scenario, we need to delay the release object. In such case we use autorelease.

In memory management, alloc opposite release which is called at end object scope. As per memory rule, variable fullName will be deallocated before its returned and thus method will return an invalid object.

Solution :

Using autorelease you tell that you want to release the ownership, but allow the caller method to use return string before its deallocated.

Thus an autorelease object will be added in the autorelease pool. All autorelease object release if that pool gets a release.

Hence Autorelease delays the release of an object.so that objects ownership given to respective method before object release.

In the next article, we will see the objective questions example on retain count.

https://medium.com/@35df9d65780f/7b7cba54aa2a?sk=

--

--